/*
 * Copyright (c) 2008, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Willow Garage, Inc. nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * This file contains helper functions for loading images as maps.
 *
 * Author: Brian Gerkey
 */

#include <cstring>
#include <stdexcept>

#include <stdlib.h>
#include <stdio.h>

// We use SDL_image to load the image from disk
#include <SDL/SDL_image.h>

// Use Bullet's Quaternion object to create one from Euler angles
#include <LinearMath/btQuaternion.h>

#include "map_server/image_loader.h"
#include <boost/property_tree/ptree.hpp>
#include <map_server/json_parser_fix.hpp>
#include <ros/ros.h>

// compute linear index for given map coords
#define MAP_IDX(sx, i, j) ((sx) * (j) + (i))

using namespace std;
using namespace boost::property_tree;

namespace map_server
{
typedef struct point
{
  int x;
  int y;
} MapPoint;

void 
bresenham(int x1,int y1,int x2,int y2,std::vector<int> &grid_free_x,std::vector<int> &grid_free_y)
{
  if (x1 != x2)
  {
      float k = float(y2-y1)/float(x2-x1);
      int flag = 0;
      if (abs(k)>1.)
      {
          flag=1;
          k=1./k;
          int temp;
          temp = x1;	x1=y1;	y1=temp;// 	[y1 x1]=Swap(x1,y1);           
          temp = x2;	x2=y2;	y2=temp;//	[y2 x2]=Swap(x2,y2);
      }
      int mi = (x1<x2)?x1:x2;
      int ma = (x1>x2)?x1:x2;
      int s;
      if (mi == x1)
          s = y1;
      else
          s = y2;
      float d = 0;
      for(int i=mi;i<=ma;i++)
      {
          if (0 == flag)
          {
              grid_free_x.emplace_back(i);
              grid_free_y.emplace_back(s);
          }
          else
          {
              grid_free_x.emplace_back(s);
              grid_free_y.emplace_back(i);
          }
          d = d+k;
          if(d>=1.)
          {
              d=d-1.;
              s=s+1.;
  
          }
          else if(d<=-1.)
          {
              d=d+1.;
              s=s-1.;
          }
      }
  }
  else
  {
      int sign = (y1<y2)?1:-1;
      for(int i=0;i<=abs(y2-y1);i++)
      {
          grid_free_x.emplace_back(x1);
          grid_free_y.emplace_back(y1+sign*i);
      }
  }
}

void
loadMapFromFile(std::string config_file_path, nav_msgs::GetMap::Response* resp,
                const char* fname, double res, bool negate,
                double occ_th, double free_th, double* origin,
                MapMode mode)
{
  ptree virtual_wall,virtual_wall_point;
  string uri = config_file_path+"virtual_wall.json";
//  ROS_INFO("uri:%s",uri.c_str());
  ifstream in_wall(uri.c_str());
	try{
		read_json(in_wall, virtual_wall);
	}
	catch(...)
	{
	  ROS_WARN("virtual_wall.json do not exsit");
	}
	in_wall.close();

  string uri2 = config_file_path+"virtual_wall_point.json";
  ifstream in_point(uri2.c_str());
	try{
		read_json(in_point, virtual_wall_point);
	}
	catch(...)
	{
		ROS_WARN("virtual_wall_point.json do not exsit");
	}
	in_point.close();

  vector<vector<string> > paths;
  {//get point name in every path
    ptree temp,pt_point;
    for(ptree::iterator it=virtual_wall.begin();it!=virtual_wall.end();it++)
    {
      temp = it->second;
      vector<string> path;
      try{
        pt_point = temp.get_child("point");
        for(ptree::iterator it=pt_point.begin();it!=pt_point.end();it++)
        {
          path.push_back(it->second.get_value<string>());
        }
        paths.push_back(path);
      }
      catch(...){}
    }
  }
  //get all point
  vector<MapPoint>  all_points;
  vector<string> all_points_name;
  for(ptree::iterator it=virtual_wall_point.begin();it!=virtual_wall_point.end();it++)
  {
    MapPoint point;
    try{
      ptree temp = it->second;
      point.x = temp.get<int>("gridX");
      point.y = temp.get<int>("gridY");
      all_points.push_back(point);
      string point_name = temp.get<string>("pointName");
      all_points_name.push_back(point_name);
    }
    catch(...){}
  }

  //get corresponding path's points
  vector<vector<MapPoint> > paths_points;
  for(int i=0;i<paths.size();i++) 
  {
    if(all_points.size()==0)
      break;
    vector<string> points_name = paths[i];
    vector<MapPoint> path_points;
    for(int j=0;j<points_name.size();j++) // a path
    {
      string point_name = points_name[j];
      for(int k=0;k<all_points_name.size();k++)
      {
        if(point_name == all_points_name[k])
        {
          path_points.push_back(all_points[k]);
          break;
        }
      }
    }
    paths_points.push_back(path_points);
  }

  vector<int> virtual_points_x,virtual_points_y;
  for(int i=0; i<paths_points.size();i++)
  {
    vector<MapPoint> path_points = paths_points[i];
    for(int j=0;j<path_points.size()-1;j++)
    {
      vector<int> x,y;
      bresenham(path_points[j].x,path_points[j].y,path_points[j+1].x,path_points[j+1].y,x,y);
      virtual_points_x.insert(virtual_points_x.end(),x.begin(),x.end());
      virtual_points_y.insert(virtual_points_y.end(),y.begin(),y.end());
    }
  }

  SDL_Surface* img;

  unsigned char* pixels;
  unsigned char* p;
  unsigned char value;
  int rowstride, n_channels, avg_channels;
  unsigned int i,j;
  int k;
  double occ;
  int alpha;
  int color_sum;
  double color_avg;

  // Load the image using SDL.  If we get NULL back, the image load failed.
  if(!(img = IMG_Load(fname)))
  {
    std::string errmsg = std::string("failed to open image file \"") +
            std::string(fname) + std::string("\": ") + IMG_GetError();
    throw std::runtime_error(errmsg);
  }

  // Copy the image data into the map structure
  resp->map.info.width = img->w;
  resp->map.info.height = img->h;
  resp->map.info.resolution = res;
  resp->map.info.origin.position.x = *(origin);
  resp->map.info.origin.position.y = *(origin+1);
  resp->map.info.origin.position.z = 0.0;
  btQuaternion q;
  // setEulerZYX(yaw, pitch, roll)
  q.setEulerZYX(*(origin+2), 0, 0);
  resp->map.info.origin.orientation.x = q.x();
  resp->map.info.origin.orientation.y = q.y();
  resp->map.info.origin.orientation.z = q.z();
  resp->map.info.origin.orientation.w = q.w();

  // Allocate space to hold the data
  resp->map.data.resize(resp->map.info.width * resp->map.info.height);

  // Get values that we'll need to iterate through the pixels
  rowstride = img->pitch;
  n_channels = img->format->BytesPerPixel;

  // NOTE: Trinary mode still overrides here to preserve existing behavior.
  // Alpha will be averaged in with color channels when using trinary mode.
  if (mode==TRINARY || !img->format->Amask)
    avg_channels = n_channels;
  else
    avg_channels = n_channels - 1;
  
  // Copy pixel data into the map structure
  pixels = (unsigned char*)(img->pixels);
  for(j = 0; j < resp->map.info.height; j++)
  {
    for (i = 0; i < resp->map.info.width; i++)
    {
      // Compute mean of RGB for this pixel
      p = pixels + j*rowstride + i*n_channels;
      color_sum = 0;
      for(k=0;k<avg_channels;k++)
        color_sum += *(p + (k));
      color_avg = color_sum / (double)avg_channels;
      if (n_channels == 1)
          alpha = 1;
      else
          alpha = *(p+n_channels-1);

      if(negate)
        color_avg = 255 - color_avg;

      if(mode==RAW){
          value = color_avg;
          resp->map.data[MAP_IDX(resp->map.info.width,i,resp->map.info.height - j - 1)] = value;
          continue;
      }


      // If negate is true, we consider blacker pixels free, and whiter
      // pixels free.  Otherwise, it's vice versa.
      occ = (255 - color_avg) / 255.0;

      // Apply thresholds to RGB means to determine occupancy values for
      // map.  Note that we invert the graphics-ordering of the pixels to
      // produce a map with cell (0,0) in the lower-left corner.
      if(occ > occ_th)
        value = +100;
      else if(occ < free_th)
        value = 0;
      else if(mode==TRINARY || alpha < 1.0)
        value = -1;    
      else {
        double ratio = (occ - free_th) / (occ_th - free_th);
        value = 99 * ratio;
      }

      resp->map.data[MAP_IDX(resp->map.info.width,i,resp->map.info.height - j - 1)] = value;
    }
  }
  for(int i=0; i<virtual_points_x.size();i++)
  {
    int x = virtual_points_x[i];
    int y = virtual_points_y[i];
    if(x<0 || y<0 || x>= resp->map.info.width || y>= resp->map.info.height)
      continue;
    resp->map.data[MAP_IDX(resp->map.info.width,x,y)] = 254;
  }

  SDL_FreeSurface(img);
}

}
